<%--
	JSP page to gather credit card details of the user.

	Change Log
	----------
 	Oct 09,2006 Added the text field for gathering the Card Verification Value.
--%>

<%@ page import="java.util.*,merlin.beans.*,merlin.dao.*,merlin.managers.*,merlin.servlets.*,merlin.utils.*" errorPage="mr_errhandler.jsp" %>

<jsp:useBean id="iwRegBean" class="merlin.beans.IWRegistrationBean" scope="session"/>
<jsp:setProperty name="iwRegBean" property="*"/>

<%
	// If the user is coming from the address details page, then based on whether the user
	// has selected the Cardholder details are same as the address details, populate the
	// credit card details fields so taht they get automatically displayed in this page's fields.
	String referer =  request.getHeader("referer");
	if(referer != null && referer.indexOf("mr_processAddress.jsp") > -1){

		String cardHolderName = null, postCode = null;
		StringBuffer billingAddress = new StringBuffer();

		if("T".equals(iwRegBean.getRadSameDetails())){
			// both the details are same
			cardHolderName = iwRegBean.getTxtFirstName() + " " + iwRegBean.getTxtSurname();

			String temp = iwRegBean.getTxtAddress1();
			if(temp != null && temp.length() > 0) billingAddress.append(temp);
			temp = iwRegBean.getTxtAddress2();
			if(temp != null && temp.length() > 0) billingAddress.append('\n').append(temp);
			temp = iwRegBean.getTxtTown();
			if(temp != null && temp.length() > 0) billingAddress.append('\n').append(temp);
			temp = iwRegBean.getTxtCounty();
			if(temp != null && temp.length() > 0) billingAddress.append('\n').append(temp);

			postCode = iwRegBean.getTxtPostcode();

		}else{
			// credit card details are different from address details
			cardHolderName = iwRegBean.getTxtCardForename() + " " + iwRegBean.getTxtCardSurname();

			String temp = iwRegBean.getTxtCardAddress1();
			if(temp != null && temp.length() > 0) billingAddress.append(temp);
			temp = iwRegBean.getTxtCardAddress2();
			if(temp != null && temp.length() > 0) billingAddress.append('\n').append(temp);
			temp = iwRegBean.getTxtCardTown();
			if(temp != null && temp.length() > 0) billingAddress.append('\n').append(temp);
			temp = iwRegBean.getTxtCardCounty();
			if(temp != null && temp.length() > 0) billingAddress.append('\n').append(temp);

			postCode = iwRegBean.getTxtCardPostcode();
		}

		iwRegBean.setTxtCardHolderName(cardHolderName);
		iwRegBean.setTxtBillingAddress(billingAddress.toString());
		iwRegBean.setTxtBillingPostcode(postCode);
	}
%>
<html>
<head>
	<title>Credit Card Details</title>
	<script>

		function isBlank(str){
			var len = str.length;
			if(len==0)return true;	// zero-length string
			for(i=0;i<len;i++){
				if(str.charAt(i) !=' ' && str.charAt(i) !='\n')return false; //some character is there
			}
			return true;
		}

		function goToAddressPage(frm){
			frm.action = 'mr_processAddress.jsp?<%=request.getQueryString()%>';
			frm.submit();
		}

		function submitPageForOrder(frm){
			// verify the credit card details.
			if(isBlank(frm.txtCardHolderName.value)){
				alert("Card Holder Name is required");
				frm.txtCardHolderName.focus();
				return;
			}

			if(! checkCCNumber(frm.txtCardNumber, frm.lstCardType)){
				frm.txtCardNumber.focus();
				return;
			}

            if(!checkExpirationDate(frm.txtExpiryDate)){
            	frm.txtExpiryDate.focus();
            	return;
            }
			if(frm.lstCardType.value ==	"SWITCH"){
				if(isBlank(frm.txtIssueNumber.value)){
					alert("Issue Number is required");
					frm.txtIssueNumber.focus();
					return;
				}
			}

			if(!checkCVV2(frm.txtCVV,frm.lstCardType)){
				frm.txtCVV.focus();
				return;
			}

			if(isBlank(frm.txtBillingAddress.value)){
				alert("Billing Address is required");
				frm.txtBillingAddress.focus();
				return;
			}

			if(isBlank(frm.txtBillingPostcode.value)){
				alert("Billing Postcode is required");
				frm.txtBillingPostcode.focus();
				return;
			}

            // show the message that the credit card is being processed.
			document.getElementById("divCreditCardProcessing").style.visibility = "visible";
			document.bgColor = "#F5F3EB";

   			frm.submit();
		}
	</script>


	<SCRIPT type="text/javascript" language="JavaScript 1.2">
		var card_types=new Array();
		var card_cvv2=new Array();
		card_types["VISA"] = "Visa";
		card_cvv2["VISA"] = "1";
		card_types["MC"] = "MasterCard";
		card_cvv2["MC"] = "1";
		card_types["SW"] = "Switch / UK Maestro";
		card_cvv2["SW"] = "1";
		card_types["SO"] = "Solo";
		card_cvv2["SO"] = "1";
		card_types["UKE"] = "Visa Electron";
		card_cvv2["UKE"] = "1";
		var force_cvv2 = 'Y';
		var txt_cc_number_invalid = "Credit Card checksum is invalid! Please correct";
		var current_year = parseInt('2007');
		var current_month = parseInt('02');
		var lbl_is_this_card_expired = "Is this card expired?";


		function isSwitchSolo(cardType, cardNbr) {

		var result    = false;

			var switchRules  = new Array("490302,490309,18,1","490335,490339,18,1","491101,491102,16,1","491174,491182,18,1","493600,493699,19,1","564182,564182,16,2","633300,633300,16,0","633301,633301,19,1","633302,633349,16,0","675900,675900,16,0","675901,675901,19,1","675902,675904,16,0","675905,675905,19,1","675906,675917,16,0","675918,675918,19,1","675919,675937,16,0","675938,675940,18,1","675941,675949,16,0","675950,675962,19,1","675963,675997,16,0","675998,675998,19,1","675999,675999,16,0");
			var soloRules    = new Array("633450,633453,16,0","633454,633457,16,0","633458,633460,16,0","633461,633461,18,1","633462,633472,16,0","633473,633473,18,1","633474,633475,16,0","633476,633476,19,1","633477,633477,16,0","633478,633478,18,1","633479,633480,16,0","633481,633481,19,1","633482,633489,16,0","633490,633493,16,1","633494,633494,18,1","633495,633497,16,2","633498,633498,19,1","633499,633499,18,1","676700,676700,16,0","676701,676701,19,1","676702,676702,16,0","676703,676703,18,1","676704,676704,16,0","676705,676705,19,1","676706,676707,16,2","676708,676711,16,0","676712,676715,16,0","676716,676717,16,0","676718,676718,19,1","676719,676739,16,0","676740,676740,18,1","676741,676749,16,0","676750,676762,19,1","676763,676769,16,0","676770,676770,19,1","676771,676773,16,0","676774,676774,18,1","676775,676778,16,0","676779,676779,18,1","676780,676781,16,0","676782,676782,18,1","676783,676794,16,0","676795,676795,18,1","676796,676797,16,0","676798,676798,19,1","676799,676799,16,0");

			switch(cardType) {
				case "SO": thisRules = soloRules;
					break;
				case "SW": thisRules = switchRules;
					break;
				default  : thisRules = new Array();
					break;
			}

			var ndx;
			var ruleDetails;
			var done = false;
			for(ndx = 0 ; ndx < thisRules.length && !done ; ++ndx) {
				thisRule    = thisRules[ndx];
				ruleDetails = thisRule.split(",");

				var hiPrefix        = ruleDetails[0];
				var loPrefix        = ruleDetails[1];
				var valLength       = parseInt(ruleDetails[2]);
				var issueLength     = ruleDetails[3];
				var startDateLength = ruleDetails[4];

				var cardPrefix = cardNbr.substr(0,hiPrefix.length);
				if(cardPrefix >= hiPrefix && cardPrefix <= loPrefix) {
					if(cardNbr.length == valLength) {
						result = true;
						done   = true;
					}
				}
			}

			return result;
		}

		/*
		* This function cheks the checksum of CreditCard
		* @param cc - the string with credit card number
		* @param accepted - the array of allowed CC types
		* if(accepted==null) { all CC types are allowed }
		*/
		function isCreditCard(cc,accepted) {
			cc=String(cc);
			if(cc.length<4 || cc.length>30)
				return false;

		// Start the Mod10 checksum process...
			var checksum=0;

		// Add even digits in even length strings or odd digits in odd length strings.
			for (var location=1-(cc.length%2); location<cc.length; location+=2) {
				var digit=parseInt(cc.substring(location,location+1));
				if(isNaN(digit))
					return false;
				checksum+=digit;
			}

		// Analyze odd digits in even length strings or even digits in odd length strings.
			for (var location=(cc.length%2); location<cc.length; location+=2) {
				var digit=parseInt(cc.substring(location,location+1));
				if(isNaN(digit))
					return false;
				if(digit<5)
					checksum+=digit*2;
				else
					checksum+=digit*2-9;
			}

			if(checksum%10!=0)
				return false;

			if(accepted!=null) {
				var checkPresent = false;
				var accepted_array = new Array("Diners Club","American Express","JCB","Carte Blanche","Visa","MasterCard","Australian BankCard","Discover/Novus","Switch","Solo", "enRoute");

				for (var i in accepted_array) {
					if(accepted[0] == accepted_array[i])
						checkPresent = true;
				}

			    var type="not";
				var accept=false;

				if(checkPresent == true) {
					var t=parseInt(cc.substring(0,4)), l=cc.length;

					if(t>=3000 && t<3060 && l==14)
						type="Diners Club";
					else if(isSwitchSolo("SW",cc.substring(0, cc.length)))
						type="Switch";
					else if(isSwitchSolo("SO",cc.substring(0, cc.length)))
						type="Solo";
					else if(t>=3400 && t<3500 && l==15)
						type="American Express";
					else if(t>=3528 && t<3590 && l==16)
						type="JCB";
					else if(t>=3600 && t<3700 && l==14)
						type="Diners Club";
					else if(t>=3700 && t<3800 && l==15)
						type="American Express";
					else if(t>=3800 && t<3890 && l==14)
						type="Diners Club";
					else if(t>=3890 && t<3900 && l==14)
						type="Carte Blanche";
					else if(t>=4000 && t<5000 && (l==13 || l==16))
						type="Visa";
					else if(t>=5100 && t<5600 && l==16)
						type="MasterCard";
					else if(t==5610 && l==16)
						type="Australian BankCard";
					else if(t==6011 && l==16)
						type="Discover/Novus";
					else if(t==2014 && l==15)
						type="enRoute";
					else if(t==2149 && l==15)
						type="enRoute";
					else
						type="not";
					// accepted and recognized types are not equal
				} else {
					// we don't know this card's type so pass it as correct
					return true;
				}

				return (accepted[0]==type);
			}

		  return true;
		}

		function checkCCNumber(field_cc,field_accepted) {
			var cc=field_cc.value;
			var accepted=null;
			if(field_accepted!=null)
			    accepted=new Array(card_types[field_accepted.value]);
			if (isCreditCard(cc,accepted))
		    	return true;
		  	else {
				alert(txt_cc_number_invalid);
				field_cc.focus();
				field_cc.select();
				return false;
			}
		}

		/*
		* This function checks CVV2 field
		*/
		function checkCVV2(cvv2,cc) {
			if(!cvv2 || !cc)
				return true;
			var num=cc.value;

			if (card_cvv2[num]=='' && force_cvv2 != 'Y')
				return true;
			cvv2 = cvv2.value;
			cvv2 = String(cvv2);

			if(cvv2.length==0) {
				alert("CVV2 is empty");
				return false;
			} else if(cvv2.length!=3 && cvv2.length!=4) {
				alert("CVV2 isn't correct");
				return false;
			}

			for (var location=0; location<cvv2.length; location++) {
				var digit=parseInt(cvv2.substring(location,location+1));
				if(isNaN(digit)) {
					alert("CVV2 must be a number");
					return false;
				}
			}

			return true;
		}

		/*
		* This function checks expiration CC date
		*/
		//function checkExpirationDate(ed_month, ed_year) {
		function checkExpirationDate(expiryDate) {
			var edate = expiryDate.value;
			// the required format is MMYY
			if(edate.length != 4){
				alert("Expiry date is not in MMYY format");
				return false;
			}
			// all the charaters must be digits
			for (var location=0; location<edate.length; location++) {
				var digit=parseInt(edate.substring(location,location+1));
				if(isNaN(digit)) {
					alert("All charaters in the expiry date field must be numbers");
					return false;
				}
			}

			var ed_month = edate.substring(0,2);
			var ed_year  = edate.substring(2,4);

			if(ed_year)
				var yy = parseInt(ed_year.replace(/^0/gi, ""));
			else
				var yy = current_year;
			if(ed_month)
				var mm = parseInt(ed_month.replace(/^0/gi, ""));
			else
				var mm = current_month;
			if(mm > 12){
				alert("invalid month value");
				return false;
			}
			if(yy < 1000)
				yy += 2000;
			if(yy < current_year || (yy == current_year && mm < current_month)) {
				alert(lbl_is_this_card_expired);
				return false;
			}
			return true;
		}

		/**
		*	Removes the in-line spaces from the credit card number
		*/
		function removeSpaces(obj){
			var data = obj.value;
			var cleanedData = "";
			for(var i = 0; i < data.length; i++){
				if(data.charAt(i) != ' '){
					cleanedData += data.charAt(i);
				}
			}
			obj.value = cleanedData;
		}

	</SCRIPT>

</head>

<body onfocus="document.getElementById('divCreditCardProcessing').style.visibility = 'hidden'">
    <jsp:include page="mr_header.jsp"/>
    <p/>

	<div align="center" id="divCreditCardProcessing" style="color:white;background-color:#B1730C;visibility:hidden;position:absolute;left:350px;top:350px">
		<h3 style="padding: 2px;font-family: Verdana, Helvetica, Arial, sans-serif;font-size: 15px;">&nbsp; Your credit card is being processed ! &nbsp;</h3>
	</div>

	<table align="center" width="750px" border="0">
		<tr>
			<td colspan="2" align="center" style='color:white;height:23px;font: 11px verdana,arial, sans-serif ;background:url("mr_images/LongBars-orange750.jpg") no-repeat;' >
				<h4 style="vertical-align:middle">Credit Card Details</h4>
			</td>
		</tr>
	</table>
	<div align="center">

	<table cellpadding="0" cellspacing="0" style="width: 750px;	font-family: Verdana, Helvetica, Arial, sans-serif;font-size: 11px;">
		<tr>
			<td>
				<form name="frmCreditCardDetails" method="post" action="merlin" >

					<input type="hidden" name="mode" value="saveNewIWOrder">
					<input type="hidden" name="hidSelectedReports" value="">
					<input type="hidden" name="emailSubject" value='New Order From <%=request.getParameter("emailFrom")%>'>

					<table style="width: 750px;	font-family: Verdana, Helvetica, Arial, sans-serif;font-size: 11px;">
						<tr>
							<td width="80%" align="center">
								<table style="width:100%;font-family: Verdana, Helvetica, Arial, sans-serif;font-size: 11px;">
									<tr>
										<td colspan="2" style="width:100%;font-weight:bold">Enter your card details below</td>
									</tr>
									<%
										String message = iwRegBean.getErrorMessage();
										if( message != null && ! message.equals("")){
									%>
									<tr>
										<td colspan="2" style="width:100%;color:red"><br><%= message %></td>
									</tr>
									<%
										}
										iwRegBean.setErrorMessage(null);	// clean up the last error message.
									%>
									<TR>
										<TD style="text-align:right;">Cardholder Name :</TD>
										<TD><INPUT name="txtCardHolderName" type="text" value='<jsp:getProperty name="iwRegBean" property="txtCardHolderName"/>' style="LEFT: 5px; TOP: 3px;font-family: Verdana, Helvetica, Arial, sans-serif;font-size: 11px;" ></TD>
									</TR>
									<TR>
										<TD style="text-align:right;">Card Type :</TD>
										<TD>
											<%
												String cardType = iwRegBean.getLstCardType();
											%>
											<SELECT name="lstCardType" style="WIDTH:157px;font-family: Verdana, Helvetica, Arial, sans-serif;font-size: 11px;">
												<OPTION value="VISA"    <%= "VISA".equals(cardType)    ? "selected" : "" %>>VISA</OPTION>
												<OPTION value="MC"      <%= "MC".equals(cardType)      ? "selected" : "" %>>Master Card</OPTION>
												<OPTION value="UKE"     <%= "UKE".equals(cardType)     ? "selected" : "" %>>Visa Electron</OPTION>
												<OPTION value="AMEX"    <%= "AMEX".equals(cardType)    ? "selected" : "" %>>American Express</OPTION>
												<OPTION value="SOLO"    <%= "SOLO".equals(cardType)    ? "selected" : "" %>>Solo</OPTION>
												<OPTION value="MAESTRO" <%= "MAESTRO".equals(cardType) ? "selected" : "" %>>UK Maestro</OPTION>
												<OPTION value="DC"      <%= "DC".equals(cardType)      ? "selected" : "" %>>Diners Club</OPTION>
											</SELECT>
										</TD>
									</TR>
									<TR>
										<TD style="text-align:right;">Card Number :</TD>
										<TD><INPUT name="txtCardNumber" type="text" value='<jsp:getProperty name="iwRegBean" property="txtCardNumber"/>' onblur="removeSpaces(this)" style="LEFT: 5px; TOP: 3px;font-family: Verdana, Helvetica, Arial, sans-serif;font-size: 11px;" ></TD>
									</TR>
									<TR>
										<TD style="text-align:right;">Start Date :</TD>
										<TD><INPUT type="text" name= "txtStartDate" value='<jsp:getProperty name="iwRegBean" property="txtStartDate"/>' style="WIDTH: 46px; HEIGHT: 22px;font-family: Verdana, Helvetica, Arial, sans-serif;font-size: 11px;" size=5> (where appropriate, use MMYY format, do not include the "/")</TD>
									</TR>
									<TR>
										<TD style="text-align:right;">Expiry Date :</TD>
										<TD><INPUT type="text" name= "txtExpiryDate" value='<jsp:getProperty name="iwRegBean" property="txtExpiryDate"/>' style="WIDTH: 47px; HEIGHT: 22px;font-family: Verdana, Helvetica, Arial, sans-serif;font-size: 11px;" size=6> (MMYY format, do not include the "/")</TD>
									</TR>
									<TR>
										<TD style="text-align:right;">Issue Number(switch only) :</TD>
										<TD><INPUT type="text" name= "txtIssueNumber" value='<jsp:getProperty name="iwRegBean" property="txtIssueNumber"/>' style="WIDTH: 22px; HEIGHT: 22px;font-family: Verdana, Helvetica, Arial, sans-serif;font-size: 11px;" size=2> (1 or 2 digits exactly on card)</TD>
									</TR>
									<TR>
										<TD style="text-align:right;">Card Verification Value :</TD>
										<TD><INPUT type="text" name= "txtCVV" value='<jsp:getProperty name="iwRegBean" property="txtCVV"/>' style="WIDTH: 38px; HEIGHT: 22px;font-family: Verdana, Helvetica, Arial, sans-serif;font-size: 11px;" size=4> (3 or 4 extra digits on rear of card)</TD>
									</TR>
									<TR>
										<TD style="text-align:right;">Billing Address :</BR>(not including post code)</TD>
										<TD>
											<TEXTAREA name= "txtBillingAddress" style="WIDTH: 184px; HEIGHT: 82px;font-family: Verdana, Helvetica, Arial, sans-serif;font-size: 11px;"><jsp:getProperty name="iwRegBean" property="txtBillingAddress"/></TEXTAREA>
										</TD>
									</TR>
									<TR>
										<TD style="text-align:right;">Billing Post Code :</TD>
										<TD><INPUT type="text" name= "txtBillingPostcode" value='<jsp:getProperty name="iwRegBean" property="txtBillingPostcode"/>' style="HEIGHT: 22px;font-family: Verdana, Helvetica, Arial, sans-serif;font-size: 11px;text-transform:uppercase" size=10></TD>
									</TR>
									<TR>
										<TD style="text-align:right;">Total To Be Charged :</TD>
										<TD>
											<table>
												<td><input type="text" value='<jsp:getProperty name="iwRegBean" property="txtInvoiceTotal"/>'  disabled= "true" style="HEIGHT: 22px;font-family: Verdana, Helvetica, Arial, sans-serif;font-size: 11px;"></td>
												<td style="color:red;font-family: Verdana, Helvetica, Arial, sans-serif;font-size: 11px;"><jsp:getProperty name="iwRegBean" property="hidDiscountText"/></td>
											</table>
										</TD>
									</TR>
								</table>
							</td>
							<td width="20%">
								<!-- SECURE SEAL WILL GO HERE -->
<script type="text/javascript" src="https://seal.thawte.com/getthawteseal?host_name=www.merlinscottassociates.co.uk&amp;size=M&amp;lang=en"></script>							
</td>
						</tr>
						<tr>
							<td width="50%">&nbsp;</td>
							<td width="50%">&nbsp;</td>
						</tr>
						<tr>
							<td>&nbsp;</td>
							<td>&nbsp;</td>
						</tr>
						<tr>
							<td>
								<input name="btnBack" class="input" value="Back" style="font-size: 11px; width: 130px;" type="button" onclick="goToAddressPage(this.form)">
								<input name="btnOrder" type="button" class="input" value="Order" style="font-size: 11px; width: 130px;" onclick="submitPageForOrder(this.form)">
							</td>
							<td>

							</td>
						</tr>
					</table>
				</form>
			</div>
		</td>
	</tr>
	</table>

	<jsp:include page="mr_footer.jsp"/>
</body>

</html>
